package leetcode.code0151;

import leetcode.helper.MaxDebug;

public class Solution extends Solution151 {

	@Override
	public String reverseWords(String s) {
		char[] chars = s.toCharArray();
		int len = s.length();
		int p = 0;
		int l = -1;
		while (p < len) {
			char cur = chars[p];
			if (cur != ' ' && l == -1) {
				l = p;
			} else if (cur == ' ' && l != -1) {
				this.reverse(chars, l, p);
				l = -1;
			}
			p++;
		}
		if (l != -1) {
			this.reverse(chars, l, len);
		}
		this.reverse(chars, 0, len);
		int avl = 0;
		boolean word = false;
		for (int i = 0; i < len; i++) {
			char c = chars[i];
			if (c != ' ') {
				if (avl != 0 && !word) {
					chars[avl++] = ' ';
				}
				chars[avl++] = c;
				word = true;
			} else if (word) {
				word = false;
			}
		}
		return new String(chars, 0, avl);
	}

	private void reverse(char[] chars, int l, int r) {
		r = r - 1;
		while (l < r) {
			char c = chars[l];
			chars[l] = chars[r];
			chars[r] = c;
			l++;
			r--;
		}
	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug2();
		MaxDebug.debug14(so);
		so.debug5();

	}

}
